import json
from jsonpath import JSONPath
# from crewai_tools import tool

class TextbookService:
    def __init__(self, json_data=None, file_path=None):
        if file_path:
            # 如果提供了文件路径，从文件中加载数据
            self.data = self.load_json_from_file(file_path)
        elif json_data:
            # 如果直接提供了JSON数据
            self.data = json_data
        else:
            self.data = {}

    # 从文件中读取JSON数据
    def load_json_from_file(self, file_path):
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                return json.load(f)
        except FileNotFoundError:
            print(f"Error: The file at {file_path} was not found.")
            return {}
        except json.JSONDecodeError:
            print(f"Error: The file at {file_path} is not a valid JSON.")
            return {}

    # 获取所有章节
    # @tool("获取所有章节标题")
    def get_all_chapter_titles(self):
        chapters = self.get_all_chapters()
        return [chapter['title'] for chapter in chapters]
    
    # 根据章节标题获取小节标题
    # @tool("获取小节标题")
    def get_section_titles_by_chapter(self, chapter_title):
        chapter = self.get_chapter_by_title(chapter_title)
        if chapter:
            return [section['title'] for section in chapter.get('sections', [])]
        return []
    
    def get_chapter_by_title(self, chapter_title):
        jsonpath_expr = JSONPath(f'$.chapters[?(@.title=="{chapter_title}")]')
        matches = jsonpath_expr.parse(self.data)
        return matches[0] if matches else None
    
    # 根据小节标题获取子小节
    def get_subsection_by_section(self, chapter_title, section_title):
        chapter = self.get_chapter_by_title(chapter_title)
        if chapter:
            sections = chapter.get('sections', [])
            for section in sections:
                if section['title'] == section_title:
                    return section.get('subsections', [])
        return []
    
    def get_all_chapters(self):
        jsonpath_expr = JSONPath('$.chapters')
        m = jsonpath_expr.parse(self.data)
        return m[0] 
    
if __name__ == "__main__":
    # 从文件中加载数据
    service = TextbookService(file_path="/Users/martinzhang/mt-20230221/zxjd-proj-20240405/04-development/python_tool_proj/management_principles.json")
    chapters = service.get_all_chapters()
    # for chapter in chapters:
    #     print(chapter['title'])
    cp = service.get_chapter_by_title("第一章管理的历史发展")
    scs = service.get_section_titles_by_chapter("第一章管理的历史发展")
    sc = service.get_subsection_by_section("第一章管理的历史发展", "第一节古典管理理论")
    print(cp)